import { Button, Empty, Input, Menu, Space } from 'antd';
import Carousel from './Carousel';
import styles from './index.less';
import CustomerIcon from '../components/icons/Customer';
import { actionList, searchTextList } from './const';
import { useEffect, useRef, useState } from 'react';
import HomeCard from '../components/HomeCard';
import {history, Link, useParams, useSearchParams} from '@umijs/max';
import { useRequest } from 'ahooks';
import { getBannerList, getCategoryList, postHomeGoods } from '@/services/home';
import useTouchBottom from '../hooks/useTouchBottom';
import { getUserInfo, thirdLogin } from '@/services/login';

const { Search } = Input;
const actionBtn = (data) => {
    return (
        <Button color="default" onClick={() => {
            history.push(data.url)
        }} variant="link" className={styles.actionBtn}>
            {data.icon}
            {data.name}
        </Button>
    )
}
const Home = () => {
    const [searchParams] = useSearchParams();
    const encryptedData = searchParams.get('encryptedData');

    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const [searchText, setSearchText] = useState('')
    const [pageNum, setCurrent] = useState<number>(1);
    const [categoryId, setCategoryId] = useState<any>('');
    const [isMore, setIsMore] = useState(true);
    const [list, setList] = useState<any>([]);

    useEffect(() => {
        if (encryptedData) {
            thirdLogin({encryptedData}).then((res) => {
                if (res.code === 200) {
                    localStorage.setItem('token', res.data)
                    getUserInfo().then((res) => {
                        localStorage.setItem('userInfo', JSON.stringify(res.data))
                        localStorage.setItem('isLogin', 'true')
                        history.push('/home')
                    })
                }
            })
        }
    }, [encryptedData])
    //获取轮播图数据
    const { data: bannerList } = useRequest(() => {
        return getBannerList().then((res) => {
            return res.data;
        })
    })
    //获取商品分类树
    const { data: categoryList } = useRequest(() => {
        return getCategoryList().then((res) => {
            return res.data.map((item) => {
                delete item.icon
                return item
            })
        })
    })
  
    const { run: runGetNoticeList, loading: noticeListLoading } = useRequest((data) => {
        let params: any = {
            name: searchText,
            categoryId: data.categoryId,
            pageSize: 10
        }
        if (data.type) {
            setCurrent(1) 
            params.pageNum = 1
        } else {
            params.pageNum = pageNum
        }
        return postHomeGoods(params).then((res) => {
            if (res.code === 200) {
                if (data.type) {
                    setList(res.data?.list)
                } else {
                    setList([...list, ...res.data?.list]);
                }
                if (pageNum >= Math.round(res.data.total / 10)) {
                    setIsMore(false);
                }
            }
            return res.data;
        })
    }, {
        manual: true,
    });

    // 触底加载
    useEffect(() => {
        runGetNoticeList({type: false, categoryId});
    }, []);
        
    const loadingRef = useRef<any>(null);
    useEffect(() => {
        loadingRef.current = noticeListLoading;
    }, [noticeListLoading]);
    
    const isMoreRef = useRef<any>(null);
    useEffect(() => {
    isMoreRef.current = isMore;
    }, [isMore]);
    const handleLoadMore = () => {
        if (!loadingRef.current && isMoreRef.current) {
        setCurrent(pageNum + 1);
        runGetNoticeList({type: false, categoryId});
        }
    };

    useTouchBottom(handleLoadMore);
    return (
        <div className={styles.page}>
            <div style={{ width: '1400px' }}>
                <div className={styles.top}>
                    <div className={styles.carouselPage}>
                        <Carousel data={bannerList?.homeBanner} />
                    </div>
                    <div className={styles.info}>
                        <div className={styles.ava}>
                            <img src={userInfo?.avatarUrl} style={{width: 50, height: 50, borderRadius: '50%'}} />
                            <div className={styles.name}>{userInfo?.name}</div>
                        </div>
                        <div className={styles.text}>
                            放心包材选谷雨
                        </div>
                        <Space size={30} className={styles.actionList}>
                            {
                                actionList.map((item) => {
                                    return actionBtn(item)
                                })
                            }
                        </Space>
                        <div className={styles.call} onClick={() => {
                            history.push('/service')
                        }}>
                            <CustomerIcon style={{fontSize: 40}} />
                            <div style={{marginLeft: '30%'}}>
                                <div>联系我们</div>
                                <div>免费试样</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className={styles.search}>
                    <div className={styles.searchText}>谷雨包材</div>
                    <div className={styles.searchInput}>
                        <Search value={searchText} onChange={(e) => {
                            setSearchText(e.target.value)
                        }} onSearch={() => {
                            runGetNoticeList({type: true, categoryId})
                        }} size="large" enterButton="搜索" placeholder='请输入关键字' />
                        <Space size={0}>
                            {
                                searchTextList.map((item) => {
                                    return (
                                        <Button color="default" onClick={() => setSearchText(item)} variant="link" >{item}</Button>
                                    )
                                })
                            }
                        </Space>
                    </div>
                </div>
                <div className={styles.category}>
                    <div style={{ height: 46, lineHeight: '46px', textWrap: 'nowrap' }}>分类：</div> 
                    <Menu 
                        className={styles.categoryMenu}
                        selectedKeys={categoryId}
                        onClick={({key}) => {
                            if (key === categoryId) {
                                setCategoryId('')
                                runGetNoticeList({type: true, categoryId: null});
                            } else {
                                setCategoryId(key)
                                runGetNoticeList({type: true, categoryId: key});
                            }
                        }} 
                        mode="horizontal" 
                        items={categoryList}
                    />
                </div>
                    {
                        list?.length > 0 ? 
                <div className={styles.content}>
                        {
                            list.map((item) => {
                                return (
                                    <HomeCard data={item} onClick={() => {
                                        history.push(`/details/${item.id}`)
                                    }} />
                                )
                            })
                        } 
                        
                </div> : <Empty style={{ marginTop: 20 }} />
                    }
            </div>
        </div>
    )
}

export default Home;